package obecto.mvc
{
	import flash.display.DisplayObject;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IEventDispatcher;
	
	import obecto.core.FLGlobals;
	import obecto.event.FLEvent;
	
	[Event(name="creationComplete", type="obecto.event.FLEvent")]
	public class MVCGlue extends EventDispatcher
	{
		[Bindable] protected var model : IModel;
		[Bindable] protected var view : IView;
		[Bindable] protected var controller : IController;
		[Bindable] protected var services : IServices;
		
		public function get displayObject() : DisplayObject
		{
			return view as DisplayObject;
		}
		
		public function MVCGlue(target : IEventDispatcher = null)
		{
			super(target);
			
			FLGlobals.topLevelSprite.addEventListener(Event.ENTER_FRAME, handleEnterFrame);
		}
		
		protected function initializeDependencies() : void 
		{	
			view.model = model;
			
			controller.model = model;
			controller.view = view;
			if (services != null)
			{
				controller.services = services;
			}
			controller.initialize();
		}
		
		protected function handleEnterFrame(e : Event) : void
		{
			FLGlobals.topLevelSprite.removeEventListener(Event.ENTER_FRAME, handleEnterFrame);
			
			initializeDependencies();
			
			dispatchEvent(new FLEvent(FLEvent.CREATION_COMPLETE));
		}

	}
}